﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace fileBrowser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeFileBrowser();
        }

        //初始化文件浏览器
        private void InitializeFileBrowser()
        {
            //绑定事件 
            treeView1.BeforeExpand += TreeViewBeforeExpand;
            treeView1.AfterSelect += TreeViewAfterSelect;
            listView1.DoubleClick += ListViewDoubleClick;

            //设置listView
            listView1.View = View.Details;
            listView1.Columns.Add("name", 200);
            listView1.Columns.Add("type", 100);
            listView1.Columns.Add("size", 100);

            // 加载 D 盘作为根目录
            string dDrive = @"D:\";
            if (Directory.Exists(dDrive))
            {
                LoadDirectoryTree(dDrive);
            }
            else
            {
                MessageBox.Show("D盘不存在或无法访问。", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        //加载文件夹树形结构 先只加载顶层
        private void LoadDirectoryTree(string rootPath)
        {
            DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
            TreeNode rootNode = new TreeNode(rootDirectory.Name)
            {
                Tag = rootDirectory
            };
            treeView1.Nodes.Add(rootNode);
            AddDummyNode(rootNode);
            
        }
        // 添加虚拟节点，标记为需要加载子节点
        private void AddDummyNode(TreeNode node)
        {
            node.Nodes.Add(new TreeNode("Loading...")); // 虚拟节点，用于显示展开图标
        }

        //动态加载子文件
        private void TreeViewBeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            TreeNode node = e.Node;
            if (node.Nodes[0].Text == "Loading...")
            {
                node.Nodes.Clear(); // 清除虚拟节点
                DirectoryInfo directoryInfo = node.Tag as DirectoryInfo;
                LoadSubDirectories(directoryInfo, node);
            }
        }
        //递归加载子文件
        private void LoadSubDirectories(DirectoryInfo rootDirectory, TreeNode rootNode)
        {
            try
            {
                foreach (var directory in rootDirectory.GetDirectories())
                {
                    TreeNode directoryNode = new TreeNode(directory.Name)
                    {
                        Tag = directory
                    };
                    AddDummyNode(directoryNode);
                    rootNode.Nodes.Add(directoryNode);
                    
                }
            }
            catch (UnauthorizedAccessException)
            {

            }
        }
        private void TreeViewAfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode selectedNode = e.Node;
            DirectoryInfo selectedDirectory = selectedNode.Tag as DirectoryInfo;
            LoadFilesAndDirectories(selectedDirectory);
        }
        // 加载指定目录的文件和文件夹到ListView中
        private void LoadFilesAndDirectories(DirectoryInfo directoryInfo)
        {
            listView1.Items.Clear();

            try
            {
                // 加载子文件夹
                foreach (var directory in directoryInfo.GetDirectories())
                {
                    ListViewItem item = new ListViewItem(directory.Name);
                    item.SubItems.Add("Folder");
                    item.SubItems.Add(""); // 文件夹没有大小
                    item.Tag = directory;
                    listView1.Items.Add(item);
                }

                // 加载文件
                foreach (var file in directoryInfo.GetFiles())
                {
                    ListViewItem item = new ListViewItem(file.Name);
                    item.SubItems.Add(file.Extension);
                    item.SubItems.Add(file.Length.ToString());
                    item.Tag = file;
                    listView1.Items.Add(item);
                }
            }
            catch (UnauthorizedAccessException) { } // 忽略无权限的文件夹
        }

        // 当双击ListView中的txt文件时，打开文件
        private void ListViewDoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            { 
                ListViewItem selectedItem = listView1.SelectedItems[0];
                if (selectedItem.Tag is FileInfo fileInfo)
                {
                    if (fileInfo.Extension == ".txt")
                    {
                        OpenTextFile(fileInfo);
                    }
                    else if (fileInfo.Extension == ".exe")
                    {
                        try
                        {
                            System.Diagnostics.Process.Start(fileInfo.FullName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"无法运行文件: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }


                }
            }
        }

        // 打开并显示txt文件内容
        private void OpenTextFile(FileInfo fileInfo)
        {
            try
            {
                string content = File.ReadAllText(fileInfo.FullName);
                MessageBox.Show(content, $"Viewing {fileInfo.Name}", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to open file: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void addToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 弹出输入框，输入文件夹名称
            string folderName = Microsoft.VisualBasic.Interaction.InputBox("请输入文件夹名称:", "添加新文件夹", "新文件夹");

            // 检查是否有选中的节点
            if (treeView1.SelectedNode != null)
            {
                // 获取选中的节点对应的目录路径
                DirectoryInfo selectedDirectory = treeView1.SelectedNode.Tag as DirectoryInfo;
                if (selectedDirectory != null)
                {
                    string newFolderPath = Path.Combine(selectedDirectory.FullName, folderName);

                    try
                    {
                        // 检查文件夹是否已存在
                        if (!Directory.Exists(newFolderPath))
                        {
                            Directory.CreateDirectory(newFolderPath);
                            LoadFilesAndDirectories(selectedDirectory); // 刷新当前文件夹的文件和文件夹列表
                            MessageBox.Show("新建文件夹成功");
                        }
                        else
                        {
                            MessageBox.Show("文件夹已存在");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"无法创建文件夹：{ex.Message}");
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择一个文件夹");
            }
        }

        private void 文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }



        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            InitializeFileBrowser();
        }

        private void newTextFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 弹出输入框，输入文件名
            string fileName = Microsoft.VisualBasic.Interaction.InputBox("请输入文本文件名称:", "添加文本文件", "新文本文件.txt");

            // 检查是否有选中的节点
            if (treeView1.SelectedNode != null)
            {
                // 获取选中的节点对应的目录路径
                DirectoryInfo selectedDirectory = treeView1.SelectedNode.Tag as DirectoryInfo;
                if (selectedDirectory != null)
                {
                    // 在选中的目录下创建新文本文件
                    string filePath = Path.Combine(selectedDirectory.FullName, fileName);

                    try
                    {
                        File.WriteAllText(filePath, ""); // 创建一个空文件
                        MessageBox.Show($"文本文件 '{fileName}' 已成功创建。");

                        // 刷新当前目录的文件和文件夹列表
                        LoadFilesAndDirectories(selectedDirectory);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"创建文本文件时出错: {ex.Message}");
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择一个文件夹");
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 确认是否退出
            var result = MessageBox.Show("确定要退出吗？", "退出确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                Application.Exit();
            }
        }
    }
}
